import oss2
from typing import BinaryIO, Optional
from datetime import datetime
from app.core.config import settings
from app.core.logger import logger
import uuid

class OSSService:
    def __init__(self):
        auth = oss2.Auth(settings.OSS_ACCESS_KEY_ID, settings.OSS_ACCESS_KEY_SECRET)
        self.bucket = oss2.Bucket(auth, settings.OSS_ENDPOINT, settings.OSS_BUCKET_NAME)
    
    def upload_file(
        self, 
        file: BinaryIO, 
        filename: str, 
        category: str = "general"
    ) -> str:
        try:
            ext = filename.split('.')[-1] if '.' in filename else ''
            unique_filename = f"{category}/{datetime.now().strftime('%Y%m%d')}/{uuid.uuid4().hex}.{ext}"
            
            self.bucket.put_object(unique_filename, file)
            
            url = f"https://{settings.OSS_BUCKET_NAME}.{settings.OSS_ENDPOINT}/{unique_filename}"
            logger.info(f"文件上传成功: {url}")
            return url
        except Exception as e:
            logger.error(f"文件上传失败: {str(e)}")
            raise
    
    def delete_file(self, file_url: str) -> bool:
        try:
            object_name = file_url.split(f"{settings.OSS_BUCKET_NAME}.{settings.OSS_ENDPOINT}/")[-1]
            self.bucket.delete_object(object_name)
            logger.info(f"文件删除成功: {file_url}")
            return True
        except Exception as e:
            logger.error(f"文件删除失败: {str(e)}")
            return False
    
    def get_file_url(self, object_name: str, expires: int = 3600) -> str:
        try:
            url = self.bucket.sign_url('GET', object_name, expires)
            return url
        except Exception as e:
            logger.error(f"获取文件URL失败: {str(e)}")
            raise

oss_service = OSSService()

